package com.yxt.qmgf.home.ctrl;

import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.Alert.AlertType;

import java.awt.*;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;

public class FeedbackPageController {

    @FXML
    private TextField subjectField;

    @FXML
    private CheckBox checkbox1;

    @FXML
    private CheckBox checkbox2;

    @FXML
    private CheckBox checkbox3;

    @FXML
    private TextArea contentArea;

    private static final String RECIPIENT_EMAIL = "1901757819@qq.com";

    @FXML
    private void sendWith163() {
        handleEmailSending("https://mail.163.com/");
    }

    @FXML
    private void sendWithQQ() {
        handleEmailSending("https://mail.qq.com/");
    }

    private void handleEmailSending(String mailUrl) {
        String subject = subjectField.getText().trim();
        String content = contentArea.getText().trim();

        if (subject.isEmpty() || content.isEmpty()) {
            showAlert("错误", "请填写反馈主题和内容");
            return;
        }

        // 收集复选框选中信息
        StringBuilder selectedOptions = new StringBuilder();
        if (checkbox1.isSelected()) {
            selectedOptions.append("功能问题 ");
        }
        if (checkbox2.isSelected()) {
            selectedOptions.append("界面问题 ");
        }
        if (checkbox3.isSelected()) {
            selectedOptions.append("性能问题 ");
        }

        // 将选中信息添加到内容中
        if (selectedOptions.length() > 0) {
            content = "反馈类别：" + selectedOptions.toString() + "\n\n" + content;
        }

        try {
            String encodedSubject = URLEncoder.encode(subject, "UTF-8");
            String encodedContent = URLEncoder.encode(content, "UTF-8");
            String encodedRecipient = URLEncoder.encode(RECIPIENT_EMAIL, "UTF-8");
            String mailtoUrl = mailUrl + "?to=" + encodedRecipient + "&subject=" + encodedSubject + "&body=" + encodedContent;

            Desktop desktop = Desktop.getDesktop();
            if (desktop.isSupported(Desktop.Action.BROWSE)) {
                desktop.browse(new URI(mailtoUrl));
                subjectField.clear();
                contentArea.clear();
                checkbox1.setSelected(false);
                checkbox2.setSelected(false);
                checkbox3.setSelected(false);
            } else {
                showAlert("错误", "当前系统不支持打开浏览器操作。");
            }
        } catch (URISyntaxException | IOException e) {
            showAlert("错误", "无法打开邮箱页面，请稍后再试。");
            e.printStackTrace();
        }
    }

    private void showAlert(String title, String content) {
        Alert alert = new Alert(AlertType.INFORMATION);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(content);
        alert.showAndWait();
    }
}